package sns.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import sns.bean.User;
import sns.dao.UserDao;
import sns.util.Encrypt;

@Transactional
public class UserDetailServiceImpl implements UserDetailsService {

	private UserDao userDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		if (username == null || (username = username.trim()).equals("")) {
			throw new UsernameNotFoundException("用户名为空");
		}
		User user = userDao.findByUsername(username);
		if (user == null) {
			return null;
		}
		System.out.println("I get the password and decrypt as "+ Encrypt.decrypt(user.getPassword()));
		String password = Encrypt.decrypt(user.getPassword());
		String role = "ROLE_USER";
		List<GrantedAuthority> authsList = new ArrayList<GrantedAuthority>();
		authsList.add(new GrantedAuthorityImpl(role));
		org.springframework.security.userdetails.User userdetail = new org.springframework.security.userdetails.User(
				username, password, true, true, true, true,
				authsList.toArray(new GrantedAuthority[authsList.size()]));
		return userdetail;
	}

}
